const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
app.use(express.urlencoded({extended: false}))
const userRouter = require('./router/user')
const infoRouter = require('./router/userinfo')
const joi = require('@hapi/joi') // 定义用户信息验证模块
const expressJWT = require('express-jwt') // 还原 token
const config = require('./config') 

// 定义 res.cc()
app.use((req,res,next)=>{
  res.cc = (err, status =1)=>{
    res.send({
      status,
      message: err instanceof Error || err instanceof joi.ValidationError ? err.message : err
    })
  }
  next()
})

// 解析 token
app.use(expressJWT({secret: config.jwtSecretKey }).unless({path: [/^\/api\//]}))

// 注册user路由
app.use('/api', userRouter)
// 注册 userinfo 路由
app.use('/my', infoRouter)

// 捕获错误
app.use((err,req,res,next)=>{
  if(err.name === 'UnauthorizedError'){
    return res.cc('无效的token')
  }
  res.cc(err)
})

app.listen(80,()=>{
  console.log('api server running at http://127.0.0.1')
})